package com.biscuit.page.basicservice.service;

import com.biscuit.page.basicservice.bean.RedisCache;
import com.biscuit.page.basicservice.model.enums.VerifyCodeWorkTypeEnum;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;
import com.biscuit.page.basicservice.utils.VerifyCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @author biscuit
 * @createTime 2024/5/22 20:28
 */
@Slf4j
@Service
public class CacheService {

    @Resource
    private RedisCache redisCache;

    /**
     * 校验验证码公共方法
     *
     * @param workTypeEnum   验证码类型
     * @param account    账号
     * @param verifyCode 验证码
     */
    public void checkVerifyCode(VerifyCodeWorkTypeEnum workTypeEnum, String account, String verifyCode) {
        // 参数校验
        BaseExceptionUtil.throwException(StringUtils.isNotBlank(verifyCode), "验证码为空");
        BaseExceptionUtil.throwException(Objects.nonNull(workTypeEnum), "验证码业务类型为空");

        // 获取验证码值的缓存 key
        String verifyCodeCacheKey = VerifyCodeUtil.getVerifyCodeKey(workTypeEnum.getPrefix(), account);

        // 获取验证码次数的缓存 key
        String verifyCodeCountCacheKey = VerifyCodeUtil.getVerifyPublishCountKey(workTypeEnum.getPrefix(), account);

        // 从缓存中获取验证码值
        String cacheVerifyCode = this.redisCache.get2String(verifyCodeCacheKey);

        // 判断验证码是否存在
        BaseExceptionUtil.throwException(StringUtils.isNotBlank(cacheVerifyCode), "验证码无效");

        // 判断验证码是否正确
        BaseExceptionUtil.throwException(verifyCode.equals(cacheVerifyCode), "验证码错误");

        // 验证码正确，异步删除验证码与验证码请求次数
        CompletableFuture.runAsync(() -> this.redisCache.delete(verifyCodeCountCacheKey, verifyCodeCountCacheKey));
    }

}
